package com.hjx.movie.core.system.controller.admin;

import com.hjx.movie.common.utils.Result;
import com.hjx.movie.common.utils.ResultType;
import com.hjx.movie.common.utils.tree.TreeBuilder;
import com.hjx.movie.common.utils.tree.TreeNode;
import com.hjx.movie.core.system.service.admin.IAreaService;
import com.hjx.movie.core.system.vo.AreaTreeNode;
import com.hjx.movie.persistence.system.model.IvyArea;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2021/1/30 - 16:37
 */
@Slf4j
@RestController
@RequestMapping("/area")
public class AreaController {

    @Resource
    IAreaService areaService;

    @GetMapping("/tree")
    public Result findAreaTree(@RequestParam(name = "rootAreaId") Long rootAreaId,
                              @RequestParam(name = "areaNameLike",required = false)String areaNameLike,
                              @RequestParam(name = "areaStatus",required = false)Boolean areaStatus){
        log.debug("findAreaTree接受到的入参===> rootAreaId:{},AreaNameLike:{},areaStatus:{}",rootAreaId,areaNameLike,areaStatus);
        if (StringUtils.isNotBlank(areaNameLike)||areaStatus!=null){
            List<AreaTreeNode> list =  areaService.findAreaTree(rootAreaId,areaNameLike,areaStatus);
            list.sort(Comparator.comparing(TreeNode::getNodeId));
            return Result.success(list);
        }
        return Result.success(TreeBuilder.treeSort(areaService.findAreaTree(rootAreaId,areaNameLike,areaStatus)));
    }

    @PostMapping("/add")
    public Result addArea(@RequestBody IvyArea ivyArea){
        log.debug("addArea接收到的入参===>:{}",ivyArea);
        if(areaService.addArea(ivyArea)){
            return Result.success("新增地域成功");
        }
        return Result.error(ResultType.USER_INPUT_ERROR);
    }

    @GetMapping("/delete")
    public Result deleteArea(@RequestParam("areaId")Long areaId){
        log.debug("deleteArea接收到的入参===>:{}",areaId);
        if (areaService.deleteArea(areaId)){
            return Result.success("删除地域成功");
        }
        return Result.error(ResultType.USER_INPUT_ERROR);
    }

    @PostMapping("/update")
    public Result updateArea(@RequestBody IvyArea area){
        log.debug("updateArea接收到的入参===>:{}",area);
        if (areaService.updateArea(area)){
            return Result.success("修改地域信息成功");
        }
        return Result.error(ResultType.USER_INPUT_ERROR);
    }

}
